import React, { useState, useEffect } from 'react';
import { TextField, Autocomplete, CircularProgress } from '@mui/material';
import PropsType from "prop-types";

const Dictionary = ({placeholder, label, field, type, setFieldValue, getOptionsFunc, labelKey, valueKey, multiple, disabled}) => {
  const [options, setOptions] = useState([])
  const [loading, setLoading] = useState(true)
  
  const setDictionaryOptions = async () => {
    setLoading(true)
    const dictionaryOptions = await getOptionsFunc().catch(err => {
      console.log(err)
    })
    if (dictionaryOptions && dictionaryOptions.length) {
      setOptions(dictionaryOptions)
    } else {
      setOptions([])
    }
    setLoading(false)
  }

  useEffect(() => {
    setDictionaryOptions()
  }, [])

  return (
    <>
      <Autocomplete
        disablePortal
        disabled={disabled}
        multiple={multiple}
        name={field.name}
        onChange={(e, value) => {
          if (multiple) { // 如果是多选
            let valueArr = []
            value.forEach(item => {
              valueArr.push(item[valueKey])
            })
            setFieldValue(field.name, valueArr)
          } else { // 否则就是单选
            setFieldValue(field.name, value ? value[valueKey] : null)
          }
        }}
        isOptionEqualToValue={(option, value) => option[labelKey] === value[labelKey]}
        getOptionLabel={(option) => option[labelKey]}
        options={options}
        sx={{ width: 300 }}
        renderInput={(params) => <TextField {...params} placeholder={placeholder} label={label} type={type} variant="filled" InputProps={{
          ...params.InputProps,
          endAdornment: (
            <React.Fragment>
              {loading ? <CircularProgress color="inherit" size={20} style={{position: 'relative', top: '-8px'}} /> : null}
              {params.InputProps.endAdornment}
            </React.Fragment>
          ),
        }} />}
      />
    </>
  )
}

Dictionary.propTypes = {
  placeholder: PropsType.string,
  label: PropsType.string.isRequired,
  field: PropsType.object.isRequired,
  type: PropsType.string,
  setFieldValue: PropsType.func.isRequired,
  getOptionsFunc: PropsType.func.isRequired,
  labelKey: PropsType.string,
  valueKey: PropsType.string,
  multiple: PropsType.bool,
  disabled: PropsType.bool
}

Dictionary.defaultProps = {
  placeholder: '请输入',
  type: 'text',
  labelKey: 'name',
  valueKey: 'id',
  multiple: false,
  disabled: false
}

export default Dictionary